/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *FileManageController
 * 文件管理
 *
 * 修改纪录
 * 2021-03-13 版本：1.0 donghang 创建。
 * @version 版本：1.0
 * @author 作者：donghang
 * 创建日期：2021-03-13
 */

package com.topscomm.center.controller;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.topscomm.file.FileSystemConst;
import com.topscomm.pub.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.center.controller.auto.FileManageControllerAuto;
import com.topscomm.center.pojo.FileManageEntity;
import com.topscomm.center.util.FileCenterUtil;
import com.topscomm.core.factory.FileStoreFactoryService;
import com.topscomm.file.FileInfoDTO;
import com.topscomm.file.FileProperties;
import com.topscomm.file.FileSystemConst.FileProcessProgressType;
import com.topscomm.file.FileSystemConst.FileUploadStateEnum;
import com.topscomm.file.convert.aspose.AsposeFileConvertToHtml;
import com.topscomm.file.service.FileDownloadFilter;
import com.topscomm.file.service.FileUploadFilter;
import com.topscomm.file.task.FileProcessProgressCache;
import com.topscomm.file.util.Utils;
import com.topscomm.file.watermark.ImageRemarkUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: donghang
 * @date: 2021-03-13
 * @description:文件管理Controller
 * @modify:
 */
@RestController
@RequestMapping("center/fileManage")
@Slf4j
public class FileManageController extends FileManageControllerAuto implements IFileManageController {
	/**
	 * 文件服务类
	 */
	@Autowired
	private FileStoreFactoryService fileStoreFactoryService;
	/**
	 * 文件属性
	 */
	@Autowired
	private FileProperties fileProperties;

	/**
	 * @author: donghang
	 * @date: 2021-03-13
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcesys")) {
			String value = paraMap.get("qry_sourcesys").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcesyse = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_identifier")) {
			String value = paraMap.get("qry_identifier").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and identifier = '{0}' ", value);
		}
		return sql.toString();
	}

	/**
	 * @author: donghang
	 * @date: 2021-03-13
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * 文件上传
	 *
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年8月17日上午9:07:51
	 * @modify:
	 */
	@PostMapping(value = "/uploadFile")
	public ResponseResult<Object> uploadFile(@RequestParam("file") MultipartFile file,
			@RequestParam(required = false) Map<String, Object> dataMap) {
		File attachFile = null;
		try {
			dataMap.put("usercode", this.getUserBean().getUser().getCode());
			dataMap.put("username", this.getUserBean().getUser().getName());
			// 上传文件块
			attachFile = FileCenterUtil.multipartFileToFile(file);
			String identifier = this.service.uploadFile(attachFile, dataMap);
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("identifier", identifier);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		} finally {
			if (attachFile != null)
				attachFile.delete();
		}

	}

	/**
	 * 文件块上传
	 *
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年8月17日上午9:07:51
	 * @modify:
	 */
	@PostMapping(value = "/uploadFileBlock")
	public ResponseResult<Object> uploadFileBlock(@RequestParam("file") MultipartFile file,
			@RequestParam(required = false) Map<String, Object> dataMap) {
		try {
			dataMap.put("usercode", this.getUserBean().getUser().getCode());
			dataMap.put("username", this.getUserBean().getUser().getName());
			// 上传文件块
			this.service.uploadFileBlock(file.getInputStream(), dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 上传完成，合并文件块
	 *
	 * @description:
	 * @param file
	 * @param blockEntity
	 * @return
	 * @author: donghang
	 * @date: 2020年8月17日上午9:49:08
	 * @modify:
	 */
	@PostMapping(value = "/mergeFileBlocks")
	public ResponseResult<Object> mergeFileBlocks(@RequestBody(required = false) FileManageEntity fileManageEntity) {
		if (fileManageEntity.getTotalblockcount() == 0) {
			return ResponseResult.error("缺失文件分片的总数参数");
		}
		try {
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("qry_identifiers", fileManageEntity.getIdentifier());
			Map<String, Object> uploadBlockMap = this.service.getUploadBlocks(paraMap)
					.get(fileManageEntity.getIdentifier());
			if (uploadBlockMap == null) {
				return ResponseResult.error("文件上传不完整，请重新上传");
			}
			List<Integer> uploadsBlock = (List<Integer>) (uploadBlockMap.get("uploadblocklist"));
			if (uploadsBlock == null || uploadsBlock.size() != fileManageEntity.getTotalblockcount()) {
				return ResponseResult.error("文件上传不完整，请重新上传");
			}
			// 处理合并文件
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("identifier", fileManageEntity.getIdentifier());
			if (this.service.mergeFileBlocks(fileManageEntity)) {
				dataMap.put("isfinish", true);
				return ResponseResult.ok(dataMap);
			} else {
				dataMap.put("isfinish", false);
				return ResponseResult.ok(dataMap);
			}
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * 得到上传的文件块号,支持多个文件上传
	 *
	 * @description:
	 * @return 确实的块号，已逗号分割
	 * @author: donghang
	 * @date: 2020年8月20日下午2:19:50
	 * @modify:
	 */
	@GetMapping(value = "/queryUploadBlocks")
	public ResponseResult<Object> queryUploadBlocks(@RequestParam Map<String, Object> paraMap) {
		Map<String, Map<String, Object>> fileUploadBlocks = this.service.getUploadBlocks(paraMap);
		// 处理上传块还是否有效
		this.service.processUploadBlocksValid(fileUploadBlocks);
		return ResponseResult.ok(fileUploadBlocks);
	}

	/**
	 * 查询某文件处理进度
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年5月13日下午6:40:57
	 * @modify:
	 */
	@GetMapping(value = "/queryFileProcessProgress")
	public ResponseResult<Object> queryFileProcessProgress(@RequestParam Map<String, Object> paraMap) {
		// 检查参数
		String identifier = ConvertUtil.convertToString(paraMap.get("qry_identifier"));
		if (identifier.length() == 0) {
			throw new BusinessException("参数不完整");
		}
		int progress = FileProcessProgressCache.getProgress(identifier);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("identifier", identifier);
		if (progress == FileProcessProgressType.Error) {
			// 进度失败，要再次查看数据库是否处理完成
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" 1=1 and identifier='{0}' and uploadstate='{1}'", identifier, FileUploadStateEnum.Finish);
			if (this.service.queryByWhere(sql.toString()).size() != 0) {
				dataMap.put("progress", FileProcessProgressType.Finish);
				return ResponseResult.ok(dataMap);
			} else {
				Map<String, Object> cacheMap = FileProcessProgressCache.getValue(identifier);
				if (cacheMap.containsKey("message")) {
					return ResponseResult.error(ConvertUtil.convertToString(cacheMap.get("message")));
				}
			}
		}
		dataMap.put("progress", progress);
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询文件信息
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年3月25日上午8:18:46
	 * @modify:
	 */
	@GetMapping(value = "/queryFileInfo")
	public ResponseResult<Object> queryFileInfo(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看。");
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put(FileManageEntity.FieldUploadstate, finishFileManageEntity.getUploadstate());
		dataMap.put(FileManageEntity.FieldImagecount, finishFileManageEntity.getImagecount());
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 删除
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年9月12日上午12:04:01
	 * @modify:
	 */
	@Override
	@DeleteMapping(value = "/delete")
	public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			this.service.deleteFile(paraMap);
			return ResponseResult.ok("删除成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * 下载文件
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年3月16日下午5:18:47
	 * @modify:
	 */
	@PostMapping(value = "/download")
	public void download(@RequestBody Map<String, Object> paraMap, HttpServletRequest request,
			HttpServletResponse response) {
		InputStream in = null;
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 检查参数
			if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
				throw new BusinessException("参数不完整");
			}
			// 查询文件信息
			List<FileManageEntity> tempList = this.service
					.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
			if (tempList.size() == 0) {
				throw new BusinessException("没有查询到文件");
			}
			// 调用文件服务下载
			FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(tempList.get(0));
			in = this.fileStoreFactoryService.downLoad(fileInfoDTO);
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=");
			response.setContentType("application/octet-stream");
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			throw new BusinessException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * app get请求
	 *
	 * @description:
	 * @param paraMap
	 * @param request
	 * @param response
	 * @author: donghang
	 * @date: 2021年5月18日下午5:28:05
	 * @modify:
	 */
	@GetMapping(value = "/download")
	public void downloadForGet(@RequestParam Map<String, Object> paraMap, HttpServletRequest request,
			HttpServletResponse response) {
		download(paraMap, request, response);
	}

	/**
	 * 预览显示，添加水印
	 *
	 * @description:
	 * @param paraMap，通过文件名查询minio服务器文件
	 * @param request
	 * @param response
	 * @author: donghang
	 * @date: 2021年3月24日下午7:45:43
	 * @modify:
	 */
	@PostMapping(value = "/displayImagePage")
	public void displayImagePage(@RequestBody Map<String, Object> paraMap, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// paraMap = BaseUtil.decodeSecureMap(paraMap);
			String identifier = ConvertUtil.convertToString(paraMap.get("qry_identifier"));
			// 文件名字
			String imageNum = ConvertUtil.convertToString(paraMap.get("qry_num"));
			// 检查参数
			if (identifier.length() == 0 || imageNum.length() == 0) {
				throw new BusinessException("参数不完整");
			}
			// 查询文件信息
			List<FileManageEntity> tempList = this.service
					.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
			if (tempList.size() != 1) {
				throw new BusinessException("没有查询到文件");
			}
			// 调用文件服务下载
			String fileName = tempList.get(0).getIdentifier() + "_" + tempList.get(0).getImagecount() + "_" + imageNum
					+ ".png";
			FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(tempList.get(0), fileName);

			InputStream inputStream = this.fileStoreFactoryService.downLoad(fileInfoDTO);
			// 添加水印
			Color color = Color.lightGray;
			ImageRemarkUtil.markImageByMoreText(inputStream, response.getOutputStream(),
					"鼎信通讯  " + this.getUserBean().getUser().getCode(), color, 45);
			String contentType = "image/png";
			response.setContentType(contentType);
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Accept-Ranges", "bytes");

		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	/**
	 * 显示文档转图片的url前缀
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年5月11日下午1:56:28
	 * @modify:
	 */
	@GetMapping(value = "/queryImagePageUrlPrefix")
	public ResponseResult<Object> displayImagePageUrlPrefix(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		String endPoint = SecurityUtil.decryptDes(fileProperties.getMinio().getEndpoint(), fileProperties.getMinio().getDecryptKey());
		dataMap.put("prefix",
				endPoint + "/" + finishFileManageEntity.getBucketname() + "/"
						+ finishFileManageEntity.getDirpath() + "/" + finishFileManageEntity.getIdentifier() + "_"
						+ finishFileManageEntity.getImagecount());
		dataMap.put("imagecount", finishFileManageEntity.getImagecount());
		return ResponseResult.ok(dataMap);
	}

	@GetMapping(value = "/queryViewFileUrl")
	public ResponseResult<Object> queryViewFileUrl(@RequestParam Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 检查参数
			if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
				return ResponseResult.error("参数不完整");
			}
			String page = ConvertUtil.convertToString(paraMap.get("page"));
			page = StringUtil.isEmpty(page) ? "1" : page;
			int total = ConvertUtil.convertToInt(paraMap.get("total"));
			total = total == 0 ? 1 : total;
			// 查询文件信息
			List<FileManageEntity> fileList = this.service
					.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
			if (fileList.size() == 0) {
				return ResponseResult.error("没有查询到文件信息");
			}
			FileManageEntity finishFileManageEntity = null;
			for (FileManageEntity fileManageEntity : fileList) {
				String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
				if (fileState.equals(FileUploadStateEnum.Finish)) {
					finishFileManageEntity = fileManageEntity;
					break;
				}
			}
			if (finishFileManageEntity == null) {
				return ResponseResult.error("文件没有处理完成。请稍后查看");
			}
			if (finishFileManageEntity.getLocation() == null) {
				return ResponseResult.error("文件不存在");
			}
			String filePath = finishFileManageEntity.getDirpath();

			FileInfoDTO fileInfo = new FileInfoDTO();
			fileInfo.setStorageType(finishFileManageEntity.getStoragetype());
			fileInfo.setBucketName(finishFileManageEntity.getBucketname());
			fileInfo.setFileDirPath(filePath);
			fileInfo.setFileId(finishFileManageEntity.getIdentifier());
			// 设置签名失效时间, 设置5分钟失效
			fileInfo.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
			fileInfo.setTimeUnit(TimeUnit.SECONDS);
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("identifier", finishFileManageEntity.getIdentifier());
			int imageTotalCount = finishFileManageEntity.getImagecount();
			dataMap.put("imagecount", imageTotalCount);
			List<Map<String, String>> list = new ArrayList<>();
			Map<String, String> map;
			total = Math.min(imageTotalCount, total);
			for (int i = 0; i < total; i++) {
				map = new HashMap<>();
				int tempPage = ConvertUtil.convertToInt(page) + i;
				String tempName = finishFileManageEntity.getIdentifier() + "_" + imageTotalCount + "_" + tempPage + ".png";
				fileInfo.setFileName(tempName);
				map.put("url", this.fileStoreFactoryService.accessUrl(fileInfo));
				map.put("index", ConvertUtil.convertToString(tempPage));
				list.add(map);
			}
			dataMap.put("list", list);
			return ResponseResult.ok(dataMap);
		} catch (Exception e) {
			return ResponseResult.error("请重试！");
		}
	}

	/**
	 *
	 * @description:
	 * @param paraMap
	 * @param request
	 * @param response
	 * @author: donghang
	 * @date: 2021年4月1日下午2:13:32
	 * @modify:
	 */
	@PostMapping(value = "/displayImage")
	public void displayImage(@RequestBody Map<String, Object> paraMap, HttpServletRequest request,
			HttpServletResponse response) {
		InputStream inputStream = null;
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String identifier = ConvertUtil.convertToString(paraMap.get("qry_identifier"));
			// 检查参数
			if (identifier.length() == 0) {
				throw new BusinessException("参数不完整");
			}
			// 查询文件信息
			List<FileManageEntity> tempList = this.service
					.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
			if (tempList.size() != 1) {
				throw new BusinessException("没有查询到文件");
			}
			// 调用文件服务下载
			FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(tempList.get(0));
			inputStream = this.fileStoreFactoryService.downLoad(fileInfoDTO);
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=");
			while ((len = inputStream.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			String contentType = "image/png";
			response.setContentType(contentType);
			response.setHeader("Content-Disposition", "attachment;filename=" + tempList.get(0).getLocation());
			response.addHeader("Accept-Ranges", "bytes");
			// inputStream.close();
		} catch (Exception e) {
			throw new BusinessException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 查询文件封面
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月1日下午11:13:24
	 * @modify:
	 */
	@GetMapping(value = "/queryTitlePages")
	public ResponseResult<Object> queryTitlePages(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询封面信息
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourcetype='{0}' and sourceid='{1}' ", FileManageEntity.tableName,
				ConvertUtil.convertToString(paraMap.get("qry_identifier")));
		List<FileManageEntity> fileList = this.service.queryByWhere(sql.toString());
		// 通过文件查询封面
		List<Map<String, Object>> urlList = new ArrayList<>();
		for (FileManageEntity finishFileManageEntity : fileList) {
			FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity);
			// 设置签名过期时间5分钟
			fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
			fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("identifier", finishFileManageEntity.getIdentifier());
			dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
			urlList.add(dataMap);
		}
		return ResponseResult.ok(urlList);
	}

	/**
	 * 查询默认封面
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月2日下午4:58:17
	 * @modify:
	 */
	@GetMapping(value = "/queryDefaultTitlePage")
	public ResponseResult<Object> queryDefaultTitlePage(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询封面信息
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourcetype='{0}' and sourceid='{1}' ", FileManageEntity.tableName,
				ConvertUtil.convertToString(paraMap.get("qry_identifier")));
		List<FileManageEntity> tempList = this.service.queryByWhere(sql.toString());
		Map<String, Object> dataMap = new HashMap<>();
		if (tempList.size() == 0) {
			return ResponseResult.ok(dataMap);
		}
		FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(tempList.get(0));
		dataMap.put("identifier", tempList.get(0).getIdentifier());
		// 设置签名失效时间, 设置5分钟
		fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
		fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月6日上午11:28:44
	 * @modify:
	 */
	@GetMapping(value = "/queryShowFileUrl")
	public ResponseResult<Object> queryShowFileUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成。请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String videoFormater = ParameterCache.getValue("FileVideoFile", "avi,mov,rmvb,rm,flv,mp4,3gp");
		String fileType = ConvertUtil.convertToString(finishFileManageEntity.getFiletype().toLowerCase());
		String fileName = "";
		FileInfoDTO fileInfoDTO;
		if (videoFormater.contains(fileType)) {
			// 视频文件需要播放mp4格式
			fileName = finishFileManageEntity.getLocation().replace("." + fileType, ".mp4");
			fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
			// 视频文件默认设置5个小时
			fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.VIDEO_SIGNATURE_EXPIRE_TIME, 18000));
			fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		} else {
			fileName = finishFileManageEntity.getLocation();
			fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
			// 普通文件设置5分钟
			fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
			fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		}
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询原始文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月6日上午11:28:44
	 * @modify:
	 */
	@GetMapping(value = "/queryOriginalFileUrl")
	public ResponseResult<Object> queryOriginalFileUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String fileName = finishFileManageEntity.getLocation();
		FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		// 普通文件设置5分钟
		fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.DOWN_LOAD_SIGNATURE_EXPIRE_TIME, 300));
		fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询html文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年5月18日下午5:17:56
	 * @modify:
	 */
	@GetMapping(value = "/queryFileHtmlUrl")
	public ResponseResult<Object> queryFileHtmlUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String fileType = ConvertUtil.convertToString(finishFileManageEntity.getFiletype().toLowerCase());
		String fileName = finishFileManageEntity.getLocation().replace("." + fileType, ".html");
		FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
		if (!this.fileStoreFactoryService.fileIsExist(fileInfoDTO)) {
			// 不存在，执行下载转换操作
			try {
				Map<String, Object> messageMap = new HashMap<String, Object>();
				messageMap.put("identifier", finishFileManageEntity.getIdentifier());
				messageMap.put("filename", ConvertUtil.convertToString(finishFileManageEntity.getIdentifier() + "."
						+ Utils.getExtension(finishFileManageEntity.getName())));
				messageMap.put("foldername", finishFileManageEntity.getDirpath());
				messageMap.put("bucketname", finishFileManageEntity.getBucketname());
				messageMap.put("storagetype", finishFileManageEntity.getStoragetype());
				// 下载
				FileDownloadFilter fileDownloadFilter = new FileDownloadFilter();
				fileDownloadFilter.doProcess(messageMap, null);
				// 转换
				StringBuilder filePath = new StringBuilder();
				filePath.append(fileProperties.getStorePath()).append("/")
						.append(finishFileManageEntity.getIdentifier()).append("/")
						.append(finishFileManageEntity.getLocation());
				StringBuilder targetFilePath = new StringBuilder();
				targetFilePath.append(fileProperties.getStorePath()).append("/")
						.append(finishFileManageEntity.getIdentifier()).toString();
				AsposeFileConvertToHtml.fileToHtml(finishFileManageEntity.getIdentifier(), filePath.toString(),
						targetFilePath.toString());
				// 上传
				FileUploadFilter fileUploadFilter = new FileUploadFilter();
				fileUploadFilter.doProcess(messageMap, null);
				// 删除文件
				StringBuilder localFileDirPath = new StringBuilder();
				localFileDirPath.append(fileProperties.getStorePath()).append("/")
						.append(ConvertUtil.convertToString(messageMap.get("identifier")));
				com.topscomm.pub.util.FileUtil.deleteDirectory(localFileDirPath.toString(), true);
			} catch (Exception e) {
				return ResponseResult.error("文件转换失败");
			}
		}
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		// 普通文件设置5分钟
		fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.DOWN_LOAD_SIGNATURE_EXPIRE_TIME, 300));
		fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}
}
